import { IListItem, IListState, ICtx } from './App';

let idCounter = 0;

// 增
export function onCreate (this: ICtx) {
    const [list, setList] = this.list;
    const [, setShowingList] = this.showingList;
    const inp: HTMLInputElement | { value: string } = document.querySelector<HTMLInputElement>('#inp') || { value: '' };
    const inpValue = inp.value;
    const newList = list.concat({
        id: ++idCounter,
        value: inpValue,
    });
    setList(newList);
    setShowingList(newList.concat());
}

// 删
export function onDelete (this: ICtx, id: IListItem['id']) {
    const [list, setList] = this.list;
    const [, setShowingList] = this.showingList;
    const newList = list.filter(({ id: currentId }) => currentId !== id);
    setList(newList);
    setShowingList(newList.concat());
}

// 查
export function onSearch (this: ICtx) {
    const [list] = this.list;
    const [, setShowingList] = this.showingList;
    const inp: HTMLInputElement | { value: string } = document.querySelector<HTMLInputElement>('#inp') || { value: '' };
    const searchValue = inp.value;
    setShowingList(list.filter(({ value }) => value.includes(searchValue)));
}

// 改
export function onEdit (this: ICtx, id: IListItem['id']) {
    const [, setEditingId] = this.editingId;
    setEditingId(id);
}

// 修改确认
export function onEditOk (this: ICtx) {
    const inp: HTMLInputElement | { value: string } = document.querySelector<HTMLInputElement>('#edit') || { value: '' };
    const editValue = inp.value;
    const [editingId, setEditingId] = this.editingId;
    const [showingList, setShowingList] = this.showingList;
    const [list, setList] = this.list;
    setEditingId(-1);
    setShowingList(showingList.map(({ id, value }) => {
        return { id, value: id === editingId ? editValue : value };
    }));
    setList(list.map(({ id, value }) => {
        return { id, value: id === editingId ? editValue : value };
    }));
}
